#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include "ip_notify_pub.h"

#define	IP_NOTIFY_PATH	"/proc/net/ipnotify"

int main( void )
{
	int fd = -1;
	fd_set rdfds;
//	struct timeval	timeout;
	struct notify_to_user *buf;
	ssize_t len = 0;

	buf = ( struct notify_to_user * )malloc( sizeof( struct notify_to_user ) );
	if ( !buf ) {
		printf( "Malloc memory for receive buffer failed.\n" );
		return -1;
	}

	memset( buf, 0, sizeof( struct notify_to_user ) );
	
	fd = open( IP_NOTIFY_PATH, O_RDWR, 0777 );
	if ( -1 == fd ) {
		printf( "Open file %s failed.\n",  IP_NOTIFY_PATH);
		goto free_mm;
	}

	for ( ; ; ) {
		FD_ZERO( &rdfds );
		FD_SET( fd, &rdfds );
		
		switch ( select( fd + 1, &rdfds, NULL, NULL, NULL ) ) {
		case -1:
			printf( "Select listen %s failed exit.\n", IP_NOTIFY_PATH );
			goto free_mm;

		case 0:
			printf( "Select listen timeout.\n" );
			break;

		default:
			printf( "%s %d.\n", __FUNCTION__, __LINE__ );
			if ( FD_ISSET( fd, &rdfds )) {
				len = read( fd, buf, sizeof( struct notify_to_user ) );
				if ( len < 0 ) {
					printf( "Read file failed.\n" );
					goto free_mm;
				}

				printf( "len = [ %d ] SIP: [ 0x%x ], DIP: [0x%x], SPORT: [%u], DPORT[%u] protocol[ %u ].\n",
					len, ntohl( buf->sip ), ntohl( buf->dip ), ntohs( buf->sport ), 
					ntohs( buf->dport ), buf->proto );
				
				memset( buf, 0, sizeof( struct notify_to_user ) );
			}

			break;
		}
	}
	
	/* dameon process. */
	//daemonize();
	
free_mm:
	if ( buf )
		free( buf );
	
}

